import 'package:fancy_shimmer_image/fancy_shimmer_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:loading_more_list/loading_more_list.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh_notification/pull_to_refresh_notification.dart';
import 'package:qianyi/controller/imageDetailVideoController.dart';
import 'package:qianyi/pages/home/mine/dongtai/rounded_rectangle_tabbar.dart';
import 'package:qianyi/pages/home/mine/dongtai/smooth_indicator_tabbar.dart';
import 'package:qianyi/state/token.dart';
import 'package:qianyi/view_model/mine/collection_view_model.dart';

import '../../../../entity/mine/Collection.dart';
import '../../../../ui/widget/custom_refresh.dart';
import '../../network/http_config.dart';
import '../../network/http_manager.dart';
import '../../pages/home/mine/dongtai/PageViewMine.dart';
import '../../ui/watefall/common/widget/push_to_refresh_header.dart';
import '../../utils/throttle.dart';
import 'CollectionViewModel.dart';

class ImageImageColloectionMine extends StatefulWidget {
  @override
  _ColloectionMineState createState() => _ColloectionMineState();
}

class _ColloectionMineState extends State<ImageImageColloectionMine> {
  final PageController _pageController = PageController(initialPage: 0);

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          CustomTabBar(
            tabs: ['专辑', '图片'],
            pageController: _pageController,
          ),
          Expanded(
            child: PageView(
              controller: _pageController,
              children: [
                AlbumPage(),
                ImagePage(),

              ],
            ),
          ),
        ],
      ),
    );
  }
}
class AlbumPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
        create: (BuildContext context) => ImageCollectionViewModel(3),
        child: Consumer<ImageCollectionViewModel>(
            builder: (context, viewModel, child) {
              viewModel.datas;
              return CustomRefresh(
                isMaterialHeader:true,
                controller: viewModel.refreshController,
                enablePullUp: true,
                onRefresh: () async {
                  viewModel.onRefresh();
                },
                onLoading: () async {
                  viewModel.onLoading();
                },
                child:
                MasonryGridView.count(
                  padding: EdgeInsets.all(2),
                  // 展示几列
                  crossAxisCount: 2,
                  mainAxisSpacing: 4, // 纵向间距
                  crossAxisSpacing: 4, // 横向间距

                  // 元素总个数
                  itemCount: viewModel.datas.length,
                  // 单个子元素
                  itemBuilder: (BuildContext context, int index) {
                    Collection album = viewModel.datas[index];

                    return  Card(
                      child: Column(
                        children: [
                          FancyShimmerImage(
                            height: getRandomHeight(),
                            imageUrl: album.cover!,
                            boxFit: BoxFit.cover,errorWidget:Image(
                            image: AssetImage("assets/icon/Snipaste_2024-11-19_08-53-03.jpg"),
                            fit: BoxFit.cover, // 根据需要选择 BoxFit
                          ),)
                          ,Text('${album.name}',style: TextStyle(
                              fontWeight: FontWeight.w400
                          ),),

                          Text("${album.imgCount}张图片 | ${album.collectionCount}人收藏")


                        ],
                      ),
                    );;
                  },


                  //本身不滚动，让外面的singlescrollview来滚动
                  physics:const NeverScrollableScrollPhysics(),
                  shrinkWrap: true, //收缩，让元素宽度自适应
                ),


              );
            })
    )
    ;
  }
}

class ImagePage extends StatelessWidget {
  DateTime? dateTimeNow;

  TokenController tokenController = Get.find();
  ImageDetailVideoController imageDetailVideoController = Get.find();
  CollectionViewUserRepository listSourceRepository = CollectionViewUserRepository();

  Widget buildWaterfallFlowItem1(BuildContext c, Collection item, int index,
      {bool konwSized = true}) {
    const double fontSize = 12.0;

    Collection album = item;

    return GestureDetector(
      onTap: () async {
        HudUtil.showBeautiful(c);
        String uid = await tokenController.getUid();
        Map<String,dynamic> params = {
          "mid":album.mid,
          "uid": uid
        };
        HttpManager.getInstance().request(url: '/platform/browseRecord/addBrowseRecord',method: Method.post,params: params);
        imageDetailVideoController.imageDetailId.value = album.mid!;
        await imageDetailVideoController.getImageVideoDetail();
        HudUtil.dismiss();
        Get.toNamed("/ui/home/imageVideoDetail");
      },
      child: Card(
        child: Column(
          children: [
            FancyShimmerImage(
              height: getRandomHeight(),
              imageUrl: album.cover!,
              boxFit: BoxFit.cover,errorWidget:Image(
              image: AssetImage("assets/icon/Snipaste_2024-11-19_08-53-03.jpg"),
              fit: BoxFit.cover, // 根据需要选择 BoxFit
            ),)
            ,
            Container(
                width: MediaQuery.of(c).size.width,
                child:   Wrap(
                  children: [
                    Text('${album.content}')
                  ],
                )
            )

            ,
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [

                Row(
                  children: [
                    ClipOval(
                        child: FancyShimmerImage(imageUrl: album.avatar as String,width: 20,height: 20,)
                    ),

                    Text(album.username as String),
                  ],
                ),

                Row(
                  children: [
                    Icon(
                      CupertinoIcons.heart,size: 14,
                      color: Colors.grey,),
                    Text('${album.count}')

                  ],
                )
              ],
            )


          ],
        ),
      ),
    );
  }

  Future<bool> onRefresh() {
    return listSourceRepository.refresh().whenComplete(() {
      dateTimeNow = DateTime.now();
    });
  }
  @override
  Widget build(BuildContext context) {
    return PullToRefreshNotification(
      pullBackOnRefresh: false,
      maxDragOffset: maxDragOffset,
      armedDragUpCancel: false,
      onRefresh: onRefresh,
      child: LoadingMoreCustomScrollView(
        slivers: <Widget>[
          SliverToBoxAdapter(
            child: PullToRefreshContainer(
                    (PullToRefreshScrollNotificationInfo? info) {
                  return PullToRefreshHeader(info, dateTimeNow);
                }),
          ),
          LoadingMoreSliverList<Collection>(
            SliverListConfig<Collection>(
              extendedListDelegate:
              const SliverWaterfallFlowDelegateWithMaxCrossAxisExtent(
                maxCrossAxisExtent: 300,
                crossAxisSpacing: 0,
                mainAxisSpacing: 1,
              ),
              itemBuilder: buildWaterfallFlowItem1,
              sourceList: listSourceRepository,
              padding: const EdgeInsets.all(1.0),
              lastChildLayoutType: LastChildLayoutType.foot,
            ),
          )
        ],
      ),
    )
      ;



  }
}




class CustomTabBar extends StatefulWidget {
  final List<String> tabs;
  final PageController pageController;

  CustomTabBar({required this.tabs, required this.pageController});

  @override
  _CustomTabBarState createState() => _CustomTabBarState();
}

class _CustomTabBarState extends State<CustomTabBar> {
  int _currentIndex = 0;

  @override
  void initState() {
    super.initState();
    _currentIndex = widget.pageController.initialPage;
    widget.pageController.addListener(() {
      setState(() {
        _currentIndex = widget.pageController.page?.round() ?? widget.pageController.initialPage;
      });
    });
  }

  @override
  void dispose() {
    widget.pageController.removeListener(() {});
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 48,
      child: Row(
        children: widget.tabs.asMap().entries.map((entry) {
          int index = entry.key;
          String tab = entry.value;
          return Expanded(
            child: GestureDetector(
              onTap: () {
                widget.pageController.jumpToPage(index);
              },
              child: Container(
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: _currentIndex == index ? Colors.grey.withOpacity(.1) : Colors.white,

                ),
                child: Text(
                  tab,
                  style: TextStyle(

                    fontWeight: _currentIndex == index ? FontWeight.bold : FontWeight.normal,
                  ),
                ),
              ),
            ),
          );
        }).toList(),
      ),
    );
  }
}